package com.shenxuchen.crm.web.controller;

import com.shenxuchen.crm.constant.Constants;
import com.shenxuchen.crm.pojo.User;
import com.shenxuchen.crm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class RouterController {

    @Resource
    private UserService userService;

    // 系统首页
    @GetMapping
    public String index(HttpSession session, HttpServletRequest request,
                        @CookieValue(value = Constants.COOKIE_USERNAME, required = false) String username,
                        @CookieValue(value = Constants.COOKIE_PASSWORD, required = false) String password) {
        // 获取登录信息，已登录跳转到首页，否则跳转到登录页面
        Object loginUser = session.getAttribute(Constants.LOGIN_USER);
        if (loginUser != null) {
            return "index";
        }

        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            String userIP = request.getRemoteAddr();
            User user = userService.autoLogin(username, password, userIP);
            if (user != null) {
                // 将用户信息保存到session中
                session.setAttribute(Constants.LOGIN_USER, user);
                return "index";
            }
        }

        return "login";
    }

    // 其它页面跳转
    @GetMapping("**/*.html")
    public String router(HttpServletRequest request) {
        String uri = request.getRequestURI();
        // /index.html ==> index
        // /activity/index.html ==> activity/index
        String viewName = uri.substring(1, uri.lastIndexOf("."));
        // 最终路径：/WEB-INF/jsp/index.jsp(前缀 + viewName + 后缀)

        return viewName;
    }
}
